package org.example.service;

import javafx.collections.ObservableList;
import org.example.controller.JavaProcessManagementController;
import org.example.controller.Loading;
import org.example.dao.SettingsRepository;
import org.example.model.ApplicationProcess;
import org.example.model.Plan;
import org.example.model.SettingsEntity;
import org.example.utils.AlertUtils;
import org.example.utils.CmdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wwy
 * @date 2020-11-28 14:50
 */
@Service
public class StartApplicationService {
    private CmdUtils cmdUtils = new CmdUtils();
    @Autowired
    private ApplicationStatusService applicationStatusService;
    @Autowired
    private JavaProcessManagementController javaProcessManagementController;
    @Autowired
    private SettingsRepository settingsRepository;
    /**
     * 拿到全局应用属性map集合
     * @return
     */
    public int startAll(Loading loading){
        List<SettingsEntity> settingsEntities = settingsRepository.findAll();
        int successCount = 0;
        int errorCount = 0;
        Map<Integer,Long> planMap = new HashMap<>();
        //获取全局表格绑定对象
        ObservableList<Plan> planData = javaProcessManagementController.getPlanData();
        Map<String, ObservableList<ApplicationProcess>> applicationDataMap = JavaProcessManagementController.applicationDataMap;
        for (Plan planDatum : planData) {
            long id = planDatum.getId();
            String priority = planDatum.getPriority();
            planMap.put(Integer.parseInt(priority),id);
        }
        //启动全部
        for (Map.Entry<Integer, Long> integerLongEntry : planMap.entrySet()) {
            Long id = integerLongEntry.getValue();
            ObservableList<ApplicationProcess> applicationProcesses = applicationDataMap.get(id+"");
            for (ApplicationProcess applicationProcess : applicationProcesses) {
                //启动
                //判断是否启动，已启动直接跳过 0:启动成功，1：已启动，2：启动失败
                int start = this.start(applicationProcess);
                if(start == 0){
                    //启动成功
                    successCount ++;
                }
                if(start == 1){
                    //已启动
                    successCount ++;
                }
                if(start == 2){
                    //启动失败
                    errorCount ++;
                }
                try {
                    if(settingsEntities !=null && settingsEntities.size()>0){
                            SettingsEntity settingsEntity = settingsEntities.get(0);
                            String startInterval = settingsEntity.getStartInterval();
                            if(!StringUtils.isEmpty(startInterval)){
                                Thread.sleep(Long.parseLong(startInterval));
                            }else{
                                Thread.sleep(1000);
                            }
                    }else{
                            Thread.sleep(1000);

                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }

                loading.showMessage("启动成功应用："+successCount+",启动失败应用："+errorCount);
            }
            try {
                if(settingsEntities !=null && settingsEntities.size()>0){
                    SettingsEntity settingsEntity = settingsEntities.get(0);
                    String planInterval = settingsEntity.getPlanInterval();
                    if(!StringUtils.isEmpty(planInterval)){
                        Thread.sleep(Long.parseLong(planInterval));
                    }else{
                        Thread.sleep(1000);
                    }
                }else{
                    Thread.sleep(1000);
                }
            }catch (Exception e) {
                e.printStackTrace();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }

        return 0;
    }
    /**
     * 启动软件
     * 首先检测软件是否启动
     * @param applicationProcess
     */
    public int start(ApplicationProcess applicationProcess){
        if(applicationProcess.getAppName().contains(".exe") || applicationProcess.getAppName().contains(".EXE")){
            //exe程序启动
            return this.startExe(applicationProcess);
        }else if(applicationProcess.getAppName().contains(".jar") || applicationProcess.getAppName().contains(".JAR")){
            //jar文件启动
            return this.startJar(applicationProcess);
        }else{
            //其他程序启动
            return this.startExe(applicationProcess);
        }
    }

    /**
     * 启动jar程序
     * @param applicationProcess
     * @return
     */
    public int startJar(ApplicationProcess applicationProcess){
        boolean b = applicationStatusService.applicationStatusByJar(applicationProcess.getAppName(),applicationProcess.getAppAddress());
        if(b){
            //已启动
            return 1;
        }
        String outstring = null;
        try {
            //Runtime.getRuntime().exec("cmd /c javaw -jar "+applicationProcess.getAppAddress());
            Desktop desktop = Desktop.getDesktop();
            desktop.open(new File(applicationProcess.getAppAddress()));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        System.out.println(outstring);
        //查看pid是否存在
        while (true){
            Map<String, String> appPidMap = applicationStatusService.getAppPidMap();
            for (Map.Entry<String, String> stringStringEntry : appPidMap.entrySet()) {
                if(stringStringEntry.getValue().equals(applicationProcess.getAppAddress())){
                    //启动成功
                    return 0;
                }
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }



    /**
     * 启动exe程序
     * @param applicationProcess
     * @return
     */
    public int startExe(ApplicationProcess applicationProcess){
        boolean b = applicationStatusService.applicationStatus(applicationProcess.getAppName(),applicationProcess.getAppAddress());
        if(b){
            //已启动
            return 1;
        }
        //启动exe应用程序
        try {
            Desktop desktop = Desktop.getDesktop();
            desktop.open(new File(applicationProcess.getAppAddress()));
            //判断进程中是否存在
            while (true){
                boolean c = applicationStatusService.applicationStatus(applicationProcess.getAppName(),applicationProcess.getAppAddress());
                if(c){
                    //已经启动
                    return 0;
                }
                Thread.sleep(500);
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 2;
    }





}
